<script setup>
  import { ref,onMounted,watch } from 'vue'
  import { ElMessage,ElMessageBox } from 'element-plus'
  import { queryEmpsList,addEmp,queryEmpById,updateEmp,deleteEmpsByIds } from '@/api/emp'
  import { queryAllDepts } from '@/api/dept'
  
  
  /**
   * 搜索栏变量
   */
  const form = ref({
    name: '',
    gender: '',
    begin: '',
    end: ''
  })

  /**
   * 查询员工
   */
  const query =async () =>{
    const result =await queryEmpsList(form.value.name,form.value.gender,form.value.begin,form.value.end,currentPage.value,pageSize.value);
    if(result.code){
      empList.value = result.data.rows;
      total.value = result.data.total;
    }
  }

  /**
   * 查询全部部门名称
   */
  const queryAllDeptsName =async ()=>{
    const result = await queryAllDepts();
    if(result.code){
      deptList.value = result.data;
    }
  }

  /**
   * 清除查询条件
   */
  const clear = () =>{
    form.value = {
      name: '',
      gender: '',
      begin: '',
      end: ''
    }
    query();
  }

  /**
   * 表格变量
   */
  const empList = ref([]);

  /**
   * 分页栏变量
   */
  //页码背景色
  const background = ref(true);
  //当前页码
  const currentPage = ref(1);
  const pageSize = ref(10);
  const total = ref(0);
  // 页面大小发生变化时触发
  const handleSizeChange = (val) => {
    query();
  }
  //当前页面发生变化时触发
  const handleCurrentChange = (val) => {
    query();
  }

  /**
   * 新增员工Dialog对话框变量
   */
  const empFormRef = ref();
  const addEmpDialogVisible  = ref(false);
  const empTitle = ref('新增员工');
  const empForm = ref({
    username: '',
    name: '',
    gender: '',
    phone: '',
    job: '',
    salary: '',
    deptId: '',
    entryDate: '',
    image: '',
    exprList: []
  })
  //点击添加员工触发
  const addEmpButton = ()=>{
    addEmpDialogVisible.value = true;//dialog对话框显示
    empForm.value = {
      username: '',
      name: '',
      gender: '',
      phone: '',
      job: '',
      salary: '',
      deptId: '',
      entryDate: '',
      image: '',
      exprList: []
    }
    empTitle.value = "新增员工";
    if (empFormRef.value){
      empFormRef.value.resetFields();
    }
  }
  //工作经历的添加
  const addExpr = ()=>{
    empForm.value.exprList.push({
      company: '',
      job: '',
      begin: '',
      end: '',
      exprDate: []
    })
  }
  //员工信息的保存
  const save =async ()=>{
    if(!empFormRef) return;
    await empFormRef.value.validate(async (valid) => {
      if (valid) {//验证通过
        let result;
        if(empForm.value.id){//修改员工数据
          result = await updateEmp(empForm.value);
        }
        else{//新增员工数据
          result = await addEmp(empForm.value);
        }
        if(result.code){//结果正常
          ElMessage.success("保存成功");
          addEmpDialogVisible.value=false;
          query();
        }
        else{//结果异常
          ElMessage.error(result.msg);
        }
      } 
      else {//验证失败
        ElMessage.error("表单验证不通过")
      }
    })
  }
  //工作经历的删除
  const deleteExpr = (index)=>{
    empForm.value.exprList.splice(index,1);
  }
  //侦听-employee员工对象中的工作经历信息
  watch(()=>empForm.value.exprList,(newValue,oldValue)=>{
    if(empForm.value.exprList && empForm.value.exprList.length>0){
      empForm.value.exprList.forEach((expr)=>{
        expr.begin = expr.exprDate[0];
        expr.end = expr.exprDate[1];
      })
    }
  },{deep:true} )//深度侦听
  //表单验证规则
  const rules = ref({
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 2, max: 20, message: '用户名长度应在2-20字之间', trigger: 'blur' }
    ],
    name: [
      { required: true, message: '请输入姓名', trigger: 'blur' },
      { min: 2, max: 10, message: '用户名长度应在2-10字之间', trigger: 'blur' }
    ],
    gender: [
      {
        required: true,
        message: '请选择性别',
        trigger: 'change'
      }
    ],
    phone: [
      { required: true, message: '请输入员工手机号', trigger: 'blur' },
      { pattern:/^1[3-9]\d{9}$/, message: '手机号格式不对', trigger: 'blur' }//^代表开始。$代表结束。\d表数字.{9}代表出现9次
    ]
  })

  /**
   * 钩子函数
   */
  onMounted(()=>{
    query();
    queryAllDeptsName();
    getToken();
  })

  /**
   * 优化下拉选项框
   */
  const genderList = ref([{name:'男',value:1},{name:'女',value:2}]);
  const jobList = ref([{name:'班主任',value:1},{name:'讲师',value:2},{name:'学工主管',value:3},{name:'教研主管',value:4},{name:'咨询师',value:5}]);
  const deptList = ref([]);

  /**
   *图片上传
   */
  //图片上传成功后触发
  const handleAvatarSuccess = (response) => {
    empForm.value.image = response.data;
  }
  //图片上传之前触发
  const beforeAvatarUpload = (rawFile) => {//rawFile代表文件，包含文件的各种属性：name、size、type、lastModifiedDate等
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
      ElMessage.error('只支持上传图片')
      return false
    } else if (rawFile.size / 1024 / 1024 > 10) {
      ElMessage.error('图片大小不能超过10MB!')
      return false
    }
    return true
  }

  /**
   * 根据id查询回显员工数据
   */
  const editEmpData =async (id)=>{
    const result =await queryEmpById(id);
    if(result.code){ 
      addEmpDialogVisible.value = true;
      empTitle.value = "修改员工";
      empForm.value = result.data;
      //对工作经历进行处理
      let exprList = empForm.value.exprList;
      if(exprList && exprList.length > 0){
        exprList.forEach((expr) => {
          expr.exprDate = [expr.begin, expr.end];
        })
      }
    }
  }

  /**
   * 根据id删除员工信息（单选）
   */
  const deleteById = (id)=>{
    ElMessageBox.confirm(
        '确定要删除该员工吗?','提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => { // 确认按钮
      console.log("删除员工：",id);
      const result =await deleteEmpsByIds([id]);
      console.log("删除结果",result);
      if(result.code){
        ElMessage.success("操作成功");
        query();
      }
      else{
        ElMessage.error(result.msg); 
      }
    })
    .catch(() => { // 取消按钮
      ElMessage.info('已取消删除')
    })
  }

  /**
  * 根据id删除员工信息（多选）
  */
 //记录勾选的员工的id
 const selectedIds = ref([]);
 //复选框勾选发生变化时触发 - selection:当前选中的记录（数组）
  const handleSelectionChange = (selection) => {
    selectedIds.value = selection.map(item => item.id);
  }
  //批量删除
  const deleteByIds = ()=>{
    ElMessageBox.confirm(
        '确定要删除该员工吗?','提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => { // 确认按钮
      if(selectedIds.value.length > 0 && selectedIds.value){
        const result =await deleteEmpsByIds(selectedIds.value);
        if(result.code){
          ElMessage.success("操作成功");
          query();
        }
        else{
          ElMessage.error(result.msg); 
        }
      }
      else{
        ElMessage.error("请选择要删除的员工");
      }
    })
    .catch(() => { // 取消按钮
      ElMessage.info('已取消删除')
    })
  }

  /**
   * 图片上传token获取
   */
  const token = ref('');
  const getToken = () =>{
    const loginUser = JSON.parse(localStorage.getItem('loginUser'));
    if(loginUser && loginUser.token){
      token.value = loginUser.token;
    }
  }

  
</script>


<template>
  <h1>员工管理</h1>
  
  <!-- 搜索栏 -->
  <div class="container">
    <el-form :inline="true" :model="form" class="demo-form-inline">
      <!-- 姓名输入 -->
      <el-form-item label="姓名" style="width: 210px">
        <el-input v-model="form.name" placeholder="请输入员工姓名" clearable/>
      </el-form-item>

      <!-- 性别选择 -->
      <el-form-item label="性别" style="width: 210px">
        <el-select v-model="form.gender" placeholder="请选择" clearable>
          <el-option label="男" value="1" />
          <el-option label="女" value="2" />
        </el-select>
      </el-form-item>

      <!-- 日期选择 -->
      <el-form-item label="入职日期">
        <el-col :span="8">
          <el-date-picker v-model="form.begin" type="date" placeholder="开始日期" style="width: 100%" value-format="YYYY-MM-DD"/>
        </el-col>

        <el-col :span="1" class="text-center">
          <span class="text-gray-500">到</span>
        </el-col>

        <el-col :span="11">
          <el-date-picker v-model="form.end" type="date" placeholder="结束日期" style="width: 100%" value-format="YYYY-MM-DD"/>
        </el-col>
      </el-form-item>
      
      <!-- 查询按钮 -->
      <el-form-item>
        <el-button type="primary" @click="query">查询</el-button>
      </el-form-item>

      <!-- 清空按钮 -->
      <el-form-item>
        <el-button type="info" @click="clear">清空</el-button>
      </el-form-item>
    </el-form>
  </div>

  <!-- 新增员工和批量删除按钮 -->
  <div class="container">
    <el-button type="primary" @click="addEmpButton"><el-icon><Plus /></el-icon>新增员工</el-button>
    <el-button type="danger" @click="deleteByIds"><el-icon><Minus /></el-icon>批量删除</el-button>
  </div>

  <!-- 表格栏 -->
  <div class="container">
    <el-table @selection-change="handleSelectionChange" :data="empList" border style="width: 100%">
      <el-table-column type="selection" width="40" align="center"/>
      <!-- property 属性用于指定该列对应表格数据对象中的 字段名（key） -->
      <el-table-column property="name" label="姓名" width="120" align="center"/>
      <el-table-column  label="性别" width="120" align="center">
        <template #default="scope">
          {{ scope.row.gender === 1 ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column property="image" label="头像" width="120" align="center">
        <template #default="scope">
          <el-image :src="scope.row.image" style="width:80px; height: 70px" />
        </template>
      </el-table-column>
      <el-table-column property="deptName" label="所属部门" width="120" align="center"/>
      <el-table-column  label="职位" width="120" align="center">
        <template #default="scope">
          <sapn v-if="scope.row.job == 1">班主任</sapn>
          <sapn v-else-if="scope.row.job == 2">讲师</sapn>
          <sapn v-else-if="scope.row.job == 3">学工主管</sapn>
          <sapn v-else-if="scope.row.job == 4">教研主管</sapn>
          <sapn v-else-if="scope.row.job == 5">咨询师</sapn>
          <sapn v-else>其他</sapn>
        </template>
      </el-table-column>
      <el-table-column property="entryDate" label="入职时间" width="120" align="center"/>
      <el-table-column property="updateTime" label="最后操作时间" width="180" align="center"/>

      <el-table-column  label="操作" align="center">
        <template #default="scope">
          <el-button size="small" type="primary" @click="editEmpData(scope.row.id)"><el-icon><EditPen /></el-icon>编辑</el-button>
          <el-button size="small" type="danger" @click="deleteById(scope.row.id)"><el-icon><Delete /></el-icon>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 分页栏 -->
  <div class="container">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5,10, 20, 30, 40]"
      :background="background"
      layout="sizes, ->, total, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <!-- 新增员工和修改员工的对话框 -->
  <el-dialog v-model="addEmpDialogVisible" :title="empTitle" >
    <!-- label-width="80px"是控制label标签的宽度 例如：用户名宽度为80px-->
    <el-form ref="empFormRef" :rules="rules" :model="empForm" label-width="80px">
      <!-- 第一行 gutter 为列间距 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="empForm.username" placeholder="请输入员工用户名，2-20个字"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="empForm.name" placeholder="请输入员工姓名，2-20个字"/>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="empForm.gender" placeholder="请选择">
              <el-option v-for="g in genderList" :key="g.value" :label="g.name" :value="g.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="empForm.phone" placeholder="请输入员工手机号，长度11位"/>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="职位">
            <el-select v-model="empForm.job" placeholder="请选择">
              <el-option v-for="j in jobList" :key="j.value" :label="j.name" :value="j.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="薪资">
            <el-input v-model="empForm.salary" placeholder="请输入员工薪资"/>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属部门">
            <el-select v-model="empForm.deptId" placeholder="请选择">
              <el-option v-for="d in deptList" :key="d.id" :label="d.name" :value="d.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职日期">
            <el-date-picker v-model="empForm.entryDate" type="date" placeholder="请选择入职日期" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第五行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="头像">
            <el-upload
              class="avatar-uploader"
              action="/api/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="{'token':token}"
            >
            <img v-if="empForm.image" :src="empForm.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第六行 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item size="small" label="工作经历">
            <el-button type="success" @click="addExpr">添加工作经历</el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第七行 -->
      <el-row :gutter="20" v-for="(expr, index) in empForm.exprList">
        <el-col :span="10">
          <el-form-item size="small" label="时间" label-width="80px">
            <el-date-picker v-model="expr.exprDate" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" ></el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item size="small" label="公司" label-width="60px">
            <el-input v-model="expr.company" placeholder="请输入公司名称"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item size="small" label="职位" label-width="60px">
            <el-input v-model="expr.job" placeholder="请输入职位"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="2">
          <el-form-item size="small" label-width="0px">
            <el-button type="danger" @click="deleteExpr(index)">删除</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 取消、确认按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addEmpDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save(empFormRef)">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>



<style scoped>
  /**
  * 外间距
  * 搜索表单与标题之间的间距
  */
  .container {
    margin-top: 30px;
    margin-bottom: 20px;
  }

  /**
   * 表格上下边距
   */
  .Table {
    margin: 20px 0;
  }

  /**
   * 新增员工部分上传图片样式
 */
 .avatar {
    height: 40px;
  }
 .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    /* 添加灰色的虚线边框 */
    border: 1px dashed var(--el-border-color);
  }
</style>